package ar.com.photo_admin.service

import ar.com.photo_admin.domain.User
import ar.com.photo_admin.exceptions.NoFacebookSessionException
import com.daureos.facebook.FacebookGraphException

class FacebookUserService {

	def facebookGraphService

	static transactional = true

	def isUserRegistered(String facebookUid) {
		return User.findByFacebookUid(facebookUid) != null
	}
	
	def findUserByFacebookId(String facebookUid) {
		return User.findByFacebookUid(facebookUid)
	}
	
	def getProfilePhotoSrc(facebookUserId) {
		facebookGraphService.getProfilePhotoSrc(facebookUserId)
	}
	
	def getUserData(String facebookUid) {
		def fbProfile = facebookGraphService.api(facebookUid, facebookGraphService.facebookData)
		if (!fbProfile)
			throw new NoFacebookSessionException()
		
		User user = new User( [
					facebookUid: facebookUid,
					username: fbProfile.username,
					birthday: fbProfile.birthday,
					email: fbProfile.email ?: null,
				])
		
		return user
	}
	
	def findOrCreateByFbUid(String facebookUid) {
		User user = User.findByFacebookUid(facebookUid)
		if (!user) {
			def fbProfile = facebookGraphService.api(facebookUid, facebookGraphService.facebookData)
			if (!fbProfile)
				throw new NoFacebookSessionException()
			user = new User( [
						facebookUid: facebookUid,
						username: fbProfile.username,
						birthday: fbProfile.birthday,
						email: fbProfile.email ?: null,
					])
			user.save(flush: true)
		}
		user
	}

	def findOrCreateByFbUidWithoutSession(String facebookUid) {
		User user = User.findByFacebookUid(facebookUid)
		if (!user) {
			def fbProfile = getPublicProfile(facebookUid)
			user = new User( [
						facebookUid: facebookUid,
						username: fbProfile.name,
						birthday: fbProfile.birthday,
						email: fbProfile.email ?: null,
					])
			user.save(flush: true)
		}
		user
	}

	def getPublicProfile(facebookUid) {
		def url = facebookGraphService.getUrl('graph', facebookUid)
		def result = facebookGraphService.makeRequest(url, [method: 'GET'])
		if(!result) throw new FacebookGraphException()
		result = JSON.parse(result)
	}
}